<template>
    <div>
           <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数分类</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区域-->
        <el-card class="box-card"> 
        <!--头部警告区域  -->
        <el-alert show-icon title="注意：只允许为第三级分类提供参数设置"  type="warning" :closable="false"> </el-alert>
        
        <!-- 选择商品分类区域 -->
        <el-row class="cat_pt">
            <el-col>
            <span>选择商品分类：</span>
                <!-- 选择商品分类级联框 -->
                <el-cascader
                      ref="cascaderRef"
                    v-model="cascaderKeys"   
                    :options="cateList"
                     expand-trigger="hover"
                    :props="cascaderProps"
                    @change="cascaderChange"
                    clearable change-on-select>
                </el-cascader>
            </el-col>
        </el-row>
        <!-- Tabs 标签页 -->
         <el-tabs v-model="activeName" @tab-click="handleTabsClick">
         <!-- 添加静态参数面板 -->
         <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisable"  @click="diglogVisble = true">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table 
            :data="manyTableData"
            border stripe
            style="width: 100%">
            <!-- 展开列 -->
            <el-table-column type=expand label=">||">
                <template slot-scope="scope">
                 <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleclose(i,scope.row)">{{item}}</el-tag>
                <!-- 动态编辑标签 -->
                <!-- 输入文本框 -->
                <el-input
                class="input-new-tag"
                 v-if="scope.row.elTagVisible"
                v-model="scope.row.elTagInputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showelTagInput(scope.row)">+ New Tag</el-button>

                </template>

            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type=index label="#"></el-table-column>
             <el-table-column prop="attr_id" label="ID" ></el-table-column>
             <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column  label="操作" width='200px'>
                <template slot-scope="scope">
                  <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.attr_id)"></el-button>
                </template>
             </el-table-column>  
            </el-table>
         </el-tab-pane>

         <!-- 添加静态属性面板 -->
         <el-tab-pane label="静态属性" name="only">

             <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="diglogVisble = true">添加属性</el-button>

              <!-- 静态参数表格 -->
            <el-table 
            :data="onlyTableData"
            border stripe
            style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type=expand label="||>">
                <template slot-scope="scope">
                 <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleclose(i,scope.row)">{{item}}</el-tag>
                <!-- 动态编辑标签 -->
                <!-- 输入文本框 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.elTagVisible"
                v-model="scope.row.elTagInputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showelTagInput(scope.row)">+ New Tag</el-button>

                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type=index label="#"></el-table-column>
             <el-table-column prop="attr_id" label="ID" ></el-table-column>
             <el-table-column prop="attr_name" label="静态属性"></el-table-column>
            <el-table-column  label="操作">
                <template slot-scope="scope">
                  <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.attr_id)"></el-button>
                </template>
             </el-table-column>  
            </el-table>

         </el-tab-pane>
         </el-tabs>

        </el-card>   

        <!-- 添加参数对话框 -->   
     <el-dialog
        :title="dialogTitle+getDialogTitle"
        :visible.sync="diglogVisble"
        width="50%"
         @close="closeDialogForm">
        <!--内容主体区域-->
        <el-form :model="dialogDataFrom" :rules="dialogDataFromRules" ref="dialogDataFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="getDialogTitle" prop="attr_name">
            <el-input v-model="dialogDataFrom.attr_name"></el-input>
        </el-form-item>

        </el-form>
         <!--底部区域-->
        <span slot="footer" class="dialog-footer">
            <el-button @click="diglogVisble = false">取 消</el-button>
            <el-button type="primary" @click="submissionData">确 定</el-button>
        </span>
     </el-dialog>

    </div>
</template>
<script>
export default {
    data() {
        return {
            //商品分类列表
            cateList:[],
             //级联选择器属性
           cascaderProps:{
                value: 'cat_id',   //选中的值
                label: 'cat_name', //看到的值
                children: 'children'//父子嵌套
           },
            //级联选择绑定的值[是一个数组] cat_id
           cascaderKeys:[],
           //被激活的Tab标签(name)
           activeName:'many',
           //动态参数列表数据
           manyTableData:[],
           //静态参数列表数据
           onlyTableData:[],
           //dialogTile标题
           dialogTitle:"添加",
           //控制对话框显示
           diglogVisble:false,
           //对话表单数据
           dialogDataFrom:{
                attr_id:"", //属性 ID
                attr_name:''//属性名字
           },
           //数据验证规则
           dialogDataFromRules:{
                  attr_name:[
                   { required: true, message: "请输入参数", trigger: 'blur' },
                   { min: 2, max: 10, message: '长度在  到10 个字符', trigger: 'blur' }
                ],
           },
    
            
        }
    },
    created() {
        this.getCateList();      
    },
    methods: {
       //获取所有的商品分类
       getCateList(){
              this.$my_http({
                  method:"get",
                  url:"categories",
                  //GET传递参数要加上params
                  params:{"type":3}   //数字1 表示仅仅展示一级。2表示展示二级。3表示展示三级
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("获取数据失败");
                    }else{  
                    this.cateList=res.data.data
                           
                 }
                }) 

       },
       //判断是否选择三级
       cascaderChange(){
          this.getParamsData();

       },
       //Tabs标签点击事件
       handleTabsClick(){
            console.log(this.activeName)
            this.getParamsData();
       },
       //请求获取参数列表的方法
       getParamsData(){

            //根据长度
           if(this.cascaderKeys.length!==3){  
                 this.$message({  message: '只能选择第三级',type: 'warning' });
                this.cascaderKeys=[];//清空
                //动态参数列表数据
               this.manyTableData=[];
             //静态参数列表数据
              this.onlyTableData=[];

               return;
           }

           //选择了三级商品则亲求参数列表(参数商品id和sel:分类静态参数还是动态参数)
             this.$my_http({
                  method:"get",
                  url:`categories/${this.cateId}/attributes`,
                  //GET传递参数要加上params
                  params:{sel:this.activeName}  
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error(res.data.meta.msg);
                    }else{  
                        //数据可能为空
                        if(res.data.data.length==0){kognzhi
                                return;
                        }
                        //循环处理数据
                        res.data.data.forEach(item => {
                            item.attr_vals =item.attr_vals ? item.attr_vals.split(","):[]//字符串切割为数组
                            //为每行数据都增加单独属性
                            item.elTagVisible =false; ////控制文本框和按钮的切换显示
                            item.elTagInputValue =''; //文本内容

                        });
                      console.log(res.data.data)
                     //动态参数数据
                     if(this.activeName=="many"){
                         this.manyTableData=res.data.data
                     }else{
                         this.onlyTableData=res.data.data
                     }
                 }
                }) 
       },
       //关闭dialog时触发
       closeDialogForm(){
            this.dialogTitle="添加";
            this.dialogDataFrom.attr_id="";
            this.dialogDataFrom.attr_name="";//清空数据
            this.$refs.dialogDataFormRef.resetFields();//重置表单
       },
       //提交dialog对话框数据
       submissionData(){
           if(!this.dialogDataFrom.attr_id){
                //添加
                this.$refs.dialogDataFormRef.validate(valid=>{           
                    if(!valid)  return;

                        this.$my_http({
                        method:"post",
                        url:`categories/${this.cateId}/attributes`,
                        data:{
                            attr_sel:this.activeName,
                            attr_name:this.dialogDataFrom.attr_name,
                            // attr_vals:''
                            }  
                        }).then(res => {
                             this.diglogVisble=false; 

                            if(res.data.meta.status != 201){
                            this.$message.error(res.data.meta.msg);
                            }else{  
                       
                            this.$message.success("创建成功");
                            this.getParamsData();
                           
                        }
                        }) 
                });
           }else{
               //修改
                this.$refs.dialogDataFormRef.validate(valid=>{           
                    if(!valid)  return;
                        this.$my_http({
                        method:"put",
                        url:`categories/${this.cateId}/attributes/${this.dialogDataFrom.attr_id}`,
                        data:{
                            attr_sel:this.activeName,
                            attr_name:this.dialogDataFrom.attr_name,
                            // attr_vals:''
                            }  
                        }).then(res => {
                             this.diglogVisble=false; 
                            if(res.data.meta.status != 200){
                            this.$message.error(res.data.meta.msg);
                            }else{  
                        
                            this.$message.success("更新成功");
                            this.getParamsData();
                           
                        }
                        }) 
                });

           }
        //在清空下
        this.closeDialogForm();  

       },
       //编辑数据
       showEditDialog(data){
            this.dialogTitle="编辑";
           this.dialogDataFrom.attr_id=data.attr_id;
           this.dialogDataFrom.attr_name=data.attr_name;
           this.diglogVisble=true; 

       },
       //删除数据
       removeDataById(attr_id){

          //确认删除则返回字符串 confirm;点击取消则报错（可使用catch 捕获错误）
          this.$confirm('正在删除用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {

                    //确定
                      this.$my_http({
                        method:"delete",
                        url:`categories/${this.cateId}/attributes/${attr_id}`,
                        }).then(res => {
                        
                            if(res.data.meta.status != 200){
                            this.$message.error(res.data.meta.msg);
                            }else{  
                        
                            this.$message.success("删除成功");
                            this.getParamsData();
                           
                        }
                        }) 
                        

                }).catch(() => {

                this.$message({ type: 'info',message: '已取消删除' });          
              });

          
       },

       //elTag文本按下回车键和失去焦点时触发
       handleInputConfirm(data){
           if(data.elTagInputValue.trim().length===0){
               data.elTagInputValue='';//清空空格
                data.elTagVisible =false//隐藏
           }else{
                //用户输入了真实数据

                data.attr_vals.push(data.elTagInputValue);//放入数组
                data.elTagInputValue="";//清空
                data.elTagVisible =false

                //发送请求保存
                 //确定
            
                      this.$my_http({
                        method:"put",
                        url:`categories/${data.cat_id}/attributes/${data.attr_id}`,
                        data:{
                            attr_sel:data.attr_sel,
                            attr_name:data.attr_name,
                            attr_vals:data.attr_vals.join(",")
                            } 
                        }).then(res => {
                        
                            if(res.data.meta.status != 200){
                            this.$message.error(res.data.meta.msg);
                            }else{  
                        
                            this.$message.success(res.data.meta.msg);
                            this.getParamsData();
                           
                        }
                        }) 
                        

           }
           
       },
       //点击按钮展示文本输入框
       showelTagInput(data){
           data.elTagVisible =true
        //让文本框自动获取焦点
        // $nextTick：当页面元素被重新渲染之后，才会指定回调函数中的代码
          this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });

       },
       //删除对应的参数可选项(关闭tag标签时触发，删除对象中数组中对应元素)
       handleclose(i,data){
           //替换i开始的长度为1的范围内的内容吧.后面还需要第3个参数,如果没有第3个参数那就表示把 i,1 的内容替换成没有,自然也就是相当于删除了第i个元素.
           console.log(i+"=============="+data.attr_vals)
           data.attr_vals.splice(i,1)

                //保存
                this.$my_http({
                        method:"put",
                        url:`categories/${data.cat_id}/attributes/${data.attr_id}`,
                        data:{
                            attr_sel:data.attr_sel,
                            attr_name:data.attr_name,
                            attr_vals:data.attr_vals.join(",")
                            } 
                        }).then(res => {
                        
                           if(res.data.meta.status != 200){
                            this.$message.error(res.data.meta.msg);
                            }else{  
                        
                            this.$message.success(res.data.meta.msg);
                            this.getParamsData();
                           
                        }
                        }) 

       }
       

    },
    //计算属性
    computed: {
        //是否禁用按钮
        isBtnDisable(){
            //不选择三级则禁用
          if(this.cascaderKeys.length!==3){ 
              return  true;
        }
        return false;
      },
      //当前选中的id
      cateId(){
          if(this.cascaderKeys.length==3){ 
              return this.cascaderKeys[2] //三级id为最后一个
          }
          return null;
      },
      //动态dialog标题属性
      getDialogTitle(){
            if(this.activeName=="many"){
                return "动态参数"
            }
            return "静态属性";
      }  
   } 
}
</script>
<style lang="less" scope>
.cat_pt{
    margin: 15px 0;
}
.el-cascader{
    width: 280px
}
.el-tag{
    margin: 5px;
}


 .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;

  }
</style>